package com.zhao.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhao.eduservice.entity.EduSubject;
import com.zhao.eduservice.entity.excel.SubjectData;
import com.zhao.eduservice.entity.subject.OneSubject;
import com.zhao.eduservice.entity.subject.TwoSubject;
import com.zhao.eduservice.listener.SubjectExcelListener;
import com.zhao.eduservice.mapper.EduSubjectMapper;
import com.zhao.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author test_java
 * @since 2022-10-14
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {


    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {

        try {
            // 文件输入流
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        // 查询一级分类
        QueryWrapper<EduSubject> wrapperOne =new QueryWrapper<>();
        wrapperOne.eq("parent_id","0");
        List<EduSubject> oneSubjectsList = baseMapper.selectList(wrapperOne);

        // 查询二级分类
        QueryWrapper<EduSubject> wrapperTwo =new QueryWrapper<>();
        wrapperTwo.ne("parent_id","0");
        List<EduSubject> twoSubjectsList = baseMapper.selectList(wrapperTwo);

        // 最终的数据
        List<OneSubject> finallySubject = new ArrayList<>();

        // 封装一级分类
        for (int i = 0; i < oneSubjectsList.size(); i++) {
            EduSubject eduSubject = oneSubjectsList.get(i);
            OneSubject oneSubjects =new OneSubject();
            BeanUtils.copyProperties(eduSubject,oneSubjects);
            finallySubject.add(oneSubjects);

            ArrayList<TwoSubject> twoFinalSubjectList = new ArrayList<>();

            for (int m = 0; m < twoSubjectsList.size(); m++) {
                EduSubject tSubject = twoSubjectsList.get(m);
                // 判断
                if (tSubject.getParentId().equals(eduSubject.getId())){
                    TwoSubject twoSubjects =new TwoSubject();
                    BeanUtils.copyProperties(tSubject,twoSubjects);
                    twoFinalSubjectList.add(twoSubjects);
                }
            }
            oneSubjects.setChildren(twoFinalSubjectList);
        }

        return finallySubject;
    }
}
